import uuid
from typing import List

from Lib import Utils
from Lib.Server import Client, server
from Lib.Utils import Console


class Room:
    def __init__(self, leader: Client, max_count: int = 4, list_member=None, room_name: str = ""):
        if list_member is None:
            list_member = []
        self.room_name = room_name
        self.uuid = uuid.uuid4().hex
        self.leader = leader
        self.max_count = max_count
        self.list_member: List[Client] = list_member
        self.all_client: List[Client] = [self.leader] + self.list_member
        # udp 协程
        port = server.GetOnlyUdpPort()
        host = "127.0.0.1"
        if port:
            self.room_udp_server, (self.udp_host, self.udp_port) = server.CreateUdpServer(self.uuid, host, port)
        else:
            Utils.Console(f"无法创建 UDP 服务。原因：无可用端口")

    def ToJson(self):
        return {
                "room_name": self.room_name,
                "uuid"     : self.uuid,
                "leader"   : self.leader.ToJson(),
                "member"   : [member.ToJson() for member in self.list_member],
                "all"      : [member.ToJson() for member in self.all_client],
                "max_count": self.max_count,
                "host"     : self.udp_host,
                "port"     : self.udp_port
        }

    def SendAll(self, data, header=None):
        if header is None:
            header = {}
        server.SendMessageToClientList(self.all_client, data, header)

    def Sync(self):
        ...
